<template>
  <div>
    <BasicModal
      @register="registerModal"
      v-bind="$attrs"
      @ok="handleSubmit"
      title="编辑设备"
      ok-text="保存"
      :closeFunc="handleClose"
    >
      <BasicForm @register="registerForm" />
    </BasicModal>
  </div>
</template>

<script setup lang="ts">
  import { ref, defineEmits } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { deviceSchemas } from './editModal.data';
  import {
    getFirmwareList,
    getSoftwareList,
    getDeviceInfo,
  } from '/@/api/thingsborad/entity/entity';
  import { modalFormStyleSetting, modalStyleSetting } from '/@/settings/thingsBoardDesign';
  import { useDebounceFn } from '@vueuse/core';

  let deviceInfo = {};
  const emit = defineEmits(['success', 'register']);
  const [registerForm, { validate, setFieldsValue, updateSchema, resetFields }] = useForm({
    layout: 'vertical',
    schemas: deviceSchemas,
    showActionButtonGroup: false,
    ...modalFormStyleSetting,
  });
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({ loading: true, confirmLoading: true, ...modalStyleSetting });
    setFieldsValue({ deviceProfileId: data?.record?.deviceProfileId?.id });
    deviceInfo = await getDeviceInfo(data.record.id);
    initSchemas(data?.record?.deviceProfileId?.id);
    setFieldsValue({
      ...data.record,
      remark: data?.record?.additionalInfo?.description,
      isGateway: data?.record?.additionalInfo?.gateway,
      isCover: data?.record?.additionalInfo?.overwriteActivityTime,
    });
    setModalProps({ loading: false, confirmLoading: false });
  });

  async function handleSubmit() {
    const values = await validate();
    setModalProps({ confirmLoading: true });
    // TODO custom api
    closeModal();
    emit('success', { key: 'edit', record: { ...deviceInfo }, values: { ...values } });
    setModalProps({ confirmLoading: false });
  }
  async function handleClose() {
    resetFields();
    return true;
  }
  function initSchemas(id: string) {
    updateSchema([
      {
        field: 'software',
        component: 'ApiSelect',
        label: '分配的软件',
        componentProps: () => {
          const params = ref({
            id,
            obj: {
              page: 0,
              pageSize: 10,
              textSearch: '',
            },
          });
          return {
            api: getSoftwareList,
            placeholder: '请选择将分发到设备的软件',
            showArrow: false,
            allowClear: false,
            showSearch: true,
            listHeight: 160,
            params: params.value,
            resultField: 'data',
            labelField: 'name',
            valueField: 'id',
            immediate: true,
            onSearch: useDebounceFn((e) => {
              params.value.obj.textSearch = e;
            }, 300),
          };
        },
      },
      {
        field: 'firmware',
        component: 'ApiSelect',
        label: '分配的固件',
        componentProps: () => {
          const params = ref({
            id,
            obj: {
              page: 0,
              pageSize: 10,
              textSearch: '',
            },
          });
          return {
            api: getFirmwareList,
            placeholder: '请选择将分发到设备的固件',
            showArrow: false,
            allowClear: false,
            showSearch: true,
            listHeight: 160,
            params: params.value,
            resultField: 'data',
            labelField: 'title',
            valueField: 'id.id',
            immediate: true,
            onSearch: useDebounceFn((e) => {
              params.value.obj.textSearch = e;
            }, 300),
          };
        },
      },
    ]);
  }
</script>
